package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Autowired
    CourseBaseMapper courseBaseMapper;


    //根据课程id查询教师
    @Override
    public List<CourseTeacher> selectByCourseId(Long courseId) {
        List<CourseTeacher> courseTeacher = courseTeacherMapper.selectByCourseId(courseId);
        if (courseTeacher.size()==0||courseTeacher==null){
            return null;
        }
        return courseTeacher;
    }

    //添加课程教师
    @Override
    public CourseTeacher addCourseTeacher(Long companyId,CourseTeacher courseTeacher) {
        //获取该课程信息，并判断companyId是否相等
        CourseBase courseBase = courseBaseMapper.selectById(courseTeacher.getCourseId());
        if(courseBase.getCompanyId().equals(companyId)){
            courseTeacher.setCreateDate(LocalDateTime.now());
            courseTeacherMapper.insert(courseTeacher);
        }else {
            throw new XueChengPlusException("只允许向机构自己的课程中添加老师、删除老师。");
        }

        return courseTeacher;
    }

    //修改课程教师
    @Override
    public CourseTeacher updateCourseTeacher(Long companyId, CourseTeacher courseTeacher) {
        //获取该课程信息，并判断companyId是否相等
        CourseBase courseBase = courseBaseMapper.selectById(courseTeacher.getCourseId());
        if(courseBase.getCompanyId().equals(companyId)){
            courseTeacher.setCreateDate(LocalDateTime.now());
            courseTeacherMapper.updateById(courseTeacher);
        }else {
            throw new XueChengPlusException("只允许向机构自己的课程中添加老师、删除老师。");
        }
        return courseTeacher;
    }


    //删除教师
    @Override
    public void deleteTeacher(Long companyId,Long courseId, Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase.getCompanyId().equals(companyId)){
            LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourseTeacher::getCourseId,courseId);
            queryWrapper.eq(CourseTeacher::getId,id);
            courseTeacherMapper.delete(queryWrapper);
        }else {
            throw new XueChengPlusException("只允许向机构自己的课程中添加老师、删除老师。");
        }
    }
}
